{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Isi Penting Generator headline news style"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Generate a long text with headline news style given isi penting (important facts)."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<div class=\"alert alert-info\">\n",
    "\n",
    "This tutorial is available as an IPython notebook at [Malaya/example/isi-penting-generator-headline-news-style](https://github.com/huseinzol05/Malaya/tree/master/example/isi-penting-generator-headline-news-style).\n",
    "    \n",
    "</div>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<div class=\"alert alert-warning\">\n",
    "\n",
    "Results generated using stochastic methods.\n",
    "    \n",
    "</div>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 2.81 s, sys: 3.91 s, total: 6.72 s\n",
      "Wall time: 2.01 s\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/home/husein/dev/malaya/malaya/tokenizer.py:214: FutureWarning: Possible nested set at position 3397\n",
      "  self.tok = re.compile(r'({})'.format('|'.join(pipeline)))\n",
      "/home/husein/dev/malaya/malaya/tokenizer.py:214: FutureWarning: Possible nested set at position 3927\n",
      "  self.tok = re.compile(r'({})'.format('|'.join(pipeline)))\n"
     ]
    }
   ],
   "source": [
    "%%time\n",
    "import malaya\n",
    "from pprint import pprint"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### List available HuggingFace"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'mesolitica/finetune-isi-penting-generator-t5-small-standard-bahasa-cased': {'Size (MB)': 242,\n",
       "  'ROUGE-1': 0.24620333,\n",
       "  'ROUGE-2': 0.05896076,\n",
       "  'ROUGE-L': 0.15158954,\n",
       "  'Suggested length': 1024},\n",
       " 'mesolitica/finetune-isi-penting-generator-t5-base-standard-bahasa-cased': {'Size (MB)': 892,\n",
       "  'ROUGE-1': 0.24620333,\n",
       "  'ROUGE-2': 0.05896076,\n",
       "  'ROUGE-L': 0.15158954,\n",
       "  'Suggested length': 1024}}"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "malaya.generator.isi_penting.available_huggingface"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "tested on semisupervised summarization on unseen AstroAwani 20 news, https://github.com/huseinzol05/malay-dataset/tree/master/summarization/semisupervised-astroawani\n",
      "each news compared ROUGE with 5 different generated texts.\n",
      "\n"
     ]
    }
   ],
   "source": [
    "print(malaya.generator.isi_penting.info)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Load HuggingFace\n",
    "\n",
    "Transformer Generator in Malaya is quite unique, most of the text generative model we found on the internet like GPT2 or Markov, simply just continue prefix input from user, but not for Transformer Generator. We want to generate an article or karangan like high school when the users give 'isi penting'.\n",
    "\n",
    "```python\n",
    "def huggingface(\n",
    "    model: str = 'mesolitica/finetune-isi-penting-generator-t5-base-standard-bahasa-cased',\n",
    "    force_check: bool = True,\n",
    "    **kwargs,\n",
    "):\n",
    "    \"\"\"\n",
    "    Load HuggingFace model to generate text based on isi penting.\n",
    "\n",
    "    Parameters\n",
    "    ----------\n",
    "    model: str, optional (default='mesolitica/finetune-isi-penting-generator-t5-base-standard-bahasa-cased')\n",
    "        Check available models at `malaya.generator.isi_penting.available_huggingface`.\n",
    "    force_check: bool, optional (default=True)\n",
    "        Force check model one of malaya model.\n",
    "        Set to False if you have your own huggingface model.\n",
    "\n",
    "    Returns\n",
    "    -------\n",
    "    result: malaya.torch_model.huggingface.IsiPentingGenerator\n",
    "    \"\"\"\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Loading the tokenizer from the `special_tokens_map.json` and the `added_tokens.json` will be removed in `transformers 5`,  it is kept for forward compatibility, but it is recommended to update your `tokenizer_config.json` by uploading it again. You will see the new `added_tokens_decoder` attribute that will store the relevant information.\n",
      "You are using the default legacy behaviour of the <class 'transformers.models.t5.tokenization_t5.T5Tokenizer'>. If you see this, DO NOT PANIC! This is expected, and simply means that the `legacy` (previous) behavior will be used so nothing changes for you. If you want to use the new behaviour, set `legacy=False`. This should only be set if you understand what it means, and thouroughly read the reason why this was added as explained in https://github.com/huggingface/transformers/pull/24565\n"
     ]
    }
   ],
   "source": [
    "model = malaya.generator.isi_penting.huggingface()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### generate\n",
    "\n",
    "```python\n",
    "def generate(\n",
    "    self,\n",
    "    strings: List[str],\n",
    "    mode: str = 'surat-khabar',\n",
    "    **kwargs,\n",
    "):\n",
    "    \"\"\"\n",
    "    generate a long text given a isi penting.\n",
    "\n",
    "    Parameters\n",
    "    ----------\n",
    "    strings : List[str]\n",
    "    mode: str, optional (default='surat-khabar')\n",
    "        Mode supported. Allowed values:\n",
    "\n",
    "        * ``'surat-khabar'`` - news style writing.\n",
    "        * ``'tajuk-surat-khabar'`` - headline news style writing.\n",
    "        * ``'artikel'`` - article style writing.\n",
    "        * ``'penerangan-produk'`` - product description style writing.\n",
    "        * ``'karangan'`` - karangan sekolah style writing.\n",
    "\n",
    "    **kwargs: vector arguments pass to huggingface `generate` method.\n",
    "        Read more at https://huggingface.co/docs/transformers/main_classes/text_generation\n",
    "\n",
    "    Returns\n",
    "    -------\n",
    "    result: List[str]\n",
    "    \"\"\"\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Good thing about HuggingFace\n",
    "\n",
    "In `generate` method, you can do greedy, beam, sampling, nucleus decoder and so much more, read it at https://huggingface.co/blog/how-to-generate\n",
    "\n",
    "And recently, huggingface released https://huggingface.co/blog/introducing-csearch"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "isi_penting = ['Dr M perlu dikekalkan sebagai perdana menteri',\n",
    "              'Muhyiddin perlulah menolong Dr M',\n",
    "              'rakyat perlu menolong Muhyiddin']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "spaces_between_special_tokens is deprecated and will be removed in transformers v5. It was adding spaces between `added_tokens`, not special tokens, and does not exist in our fast implementation. Future tokenizers will handle the decoding process on a per-model rule.\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['Presiden Umno, Ahmad Zahid Hamidi meminta agar Dr Mahathir Mohamad tidak '\n",
      " 'dikekalkan sebagai perdana menteri sementara. Dalam satu temubual bersama '\n",
      " 'stesen radio CNA, Zahid berkata Muhyiddin perlulah menolong Dr Mahathir. '\n",
      " '\"Disebabkan Mahathir telah hilang majoriti, eloklah Dr Mahathir berundur '\n",
      " 'sebagai perdana menteri sementara. \"Berilah peluang kepada Dr Mahathir '\n",
      " 'sebagai perdana menteri sementara.']\n"
     ]
    }
   ],
   "source": [
    "pprint(model.generate(isi_penting, mode = 'tajuk-surat-khabar',\n",
    "    do_sample=True, \n",
    "    max_length=256, \n",
    "    top_k=50, \n",
    "    top_p=0.95,))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['Presiden Parti Pribumi Bersatu Malaysia (Bersatu) Tan Sri Muhyiddin Yassin '\n",
      " 'menegaskan bahawa Dr Mahathir Mohamad perlu dikekalkan sebagai perdana '\n",
      " 'menteri kerana beliau mempunyai banyak kelebihan. \"Dr Mahathir perlu '\n",
      " 'dikekalkan sebagai perdana menteri kerana beliau mempunyai banyak kelebihan. '\n",
      " 'Muhyiddin juga berkata, Muhyiddin tidak boleh hanya bergantung kepada Dr '\n",
      " 'Mahathir sahaja kerana ada beberapa masalah yang perlu ditangani. \"Perlulah '\n",
      " 'menolong Dr M. \"Janganlah hanya kerana satu masalah, rakyat perlu menolong '\n",
      " 'beliau.']\n"
     ]
    }
   ],
   "source": [
    "pprint(model.generate(isi_penting, mode = 'tajuk-surat-khabar',\n",
    "    do_sample=True, \n",
    "    max_length=256, \n",
    "    penalty_alpha=0.8, top_k=4,))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "isi_penting = ['Neelofa tetap dengan keputusan untuk berkahwin akhir tahun ini',\n",
    "              'Long Tiger sanggup membantu Neelofa',\n",
    "              'Tiba-tiba Long Tiger bergaduh dengan Husein Zolkepli']"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We also can give any isi penting even does not make any sense."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['KUALA LUMPUR: Di sebalik pelbagai kecaman netizen, pengacara dan usahawan, '\n",
      " 'Neelofa tetap dengan keputusan untuk berkahwin akhir tahun ini. Neelofa yang '\n",
      " 'sedang hangat meraikan hari lahir di sebuah restoran mewah di ibu kota, '\n",
      " 'mengumumkan perkara tersebut menerusi satu entri di laman Instagram '\n",
      " 'miliknya. \"I have a chance to be berkahwin akhir tahun this year,\" tulis '\n",
      " 'Neelofa. Long Tiger sanggup membantu Neelofa. Tiba-tiba Long Tiger bergaduh '\n",
      " 'dengan teman lelakinya, Husein Zolkepli. Ketika itu, Husein sedang minum di '\n",
      " 'restoran berkenaan, yang kemudian diseret, sebelum Long Tiger sekali lagi '\n",
      " 'mencemuh Neelofa. Sumber: BH Online.']\n"
     ]
    }
   ],
   "source": [
    "pprint(model.generate(isi_penting, do_sample=True, mode = 'tajuk-surat-khabar',\n",
    "    max_length=256,\n",
    "    top_k=50, \n",
    "    top_p=0.95, ))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['KUALA LUMPUR: Pelakon dan pengacara terkenal, Neelofa tetap dengan keputusan '\n",
      " 'untuk berkahwin penghujung tahun ini. Namun, kata Neelofa, perkara itu akan '\n",
      " 'dibincangkan dalam mesyuarat yang akan diadakan tidak lama lagi. Long '\n",
      " 'Tiger,\" katanya menerusi akaun Instagramnya. Tiba-tiba Long Tiger bergaduh '\n",
      " 'dengan Husein Zolkepli. \"Long Tiger sanggup membantu Neelofa. \"Long Tiger '\n",
      " 'juga sanggup membantu Husein Zolkepli untuk mendapatkan hak perkahwinan,\" '\n",
      " 'kata Neelofa. \"Semoga Long Tiger terus tabah dan sabar menghadapi dugaan,\" '\n",
      " 'tulis Neelofa lagi. \"Sekali lagi ucapkan jutaan terima kasih kepada semua '\n",
      " 'yang mendoakan kesejahteraan dan kebahagiaan Long Tiger dan Husein.']\n"
     ]
    }
   ],
   "source": [
    "pprint(model.generate(isi_penting, mode = 'tajuk-surat-khabar',\n",
    "    do_sample=True, \n",
    "    max_length=256, \n",
    "    penalty_alpha=0.8, top_k=4,))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [],
   "source": [
    "isi_penting = ['Anwar Ibrahim jadi perdana menteri', 'Muhyiddin cemburu jadi PM tepi',\n",
    "              'PAS menggunakan isu sentimen kaum dan agama']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['Setiausaha Agung DAP, Lim Guan Eng berkata, bukan menjadi isu bagi beliau '\n",
      " 'yang juga Menteri Kewangan untuk tidak mencampuri usaha memperkukuhkan '\n",
      " 'kerajaan dan mentadbir negara. \"Sekarang (Datuk Seri) Anwar Ibrahim Ibrahim '\n",
      " 'sedang jadi perdana menteri. Muhyiddin cemburu jadi PM tepi,\" katanya, di '\n",
      " 'sini hari ini. Sebelum ini, PAS menggunakan isu sentimen kaum dan agama '\n",
      " 'untuk menarik sokongan pengundi kepada Pakatan Harapan (PH). Setiausaha '\n",
      " 'Agung PAS, TakiyuddinDecemberon dalam kenyataan menegaskan, parti itu tidak '\n",
      " 'akan menarik sokongan sebaliknya memberi tumpuan kepada usaha mengurangkan '\n",
      " 'beban rakyat.']\n"
     ]
    }
   ],
   "source": [
    "pprint(model.generate(isi_penting, do_sample=True, mode = 'tajuk-surat-khabar',\n",
    "    max_length=256))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['Presiden PAS, Abdul Hadi Awang tidak pernah menggunakan isu kaum dan agama '\n",
      " 'untuk menggambarkan dirinya sebagai seorang yang tidak bertanggungjawab. '\n",
      " 'Sebaliknya, kata beliau, PAS menggunakan isu sentimen kaum dan agama untuk '\n",
      " 'menggambarkan dirinya sebagai seorang yang tidak bertanggungjawab. \"Anwar '\n",
      " 'Ibrahim jadi perdana menteri dan Muhyiddin (Muhyiddin) cemburu jadi PM tepi.']\n"
     ]
    }
   ],
   "source": [
    "pprint(model.generate(isi_penting, mode = 'tajuk-surat-khabar',\n",
    "    do_sample=True, \n",
    "    max_length=256, \n",
    "    penalty_alpha=0.8, top_k=4,))"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.10"
  },
  "varInspector": {
   "cols": {
    "lenName": 16,
    "lenType": 16,
    "lenVar": 40
   },
   "kernels_config": {
    "python": {
     "delete_cmd_postfix": "",
     "delete_cmd_prefix": "del ",
     "library": "var_list.py",
     "varRefreshCmd": "print(var_dic_list())"
    },
    "r": {
     "delete_cmd_postfix": ") ",
     "delete_cmd_prefix": "rm(",
     "library": "var_list.r",
     "varRefreshCmd": "cat(var_dic_list()) "
    }
   },
   "types_to_exclude": [
    "module",
    "function",
    "builtin_function_or_method",
    "instance",
    "_Feature"
   ],
   "window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
